package wht.jly.forum.controller.posting;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import wht.jly.forum.domain.Posting;
import wht.jly.forum.domain.PostingType;
import wht.jly.forum.service.PostingService;
import wht.jly.forum.service.UserService;
import wht.jly.forum.utils.JsonData;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author lanyangji
 * @date 2019/2/13 17:43
 */
@Slf4j
@Controller
@RequestMapping("/posting")
public class PostingController {

    @Autowired
    private PostingService postingService;

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public String postingDetail(@PathVariable("id") Integer id, Model model) {
        model.addAttribute("postingDTO", postingService.findById(id));

        return "details";
    }

    @PostMapping
    @ResponseBody
    public JsonData posting(Posting posting, HttpServletRequest request) {
        // 组装枚举类型
        String postingTypeIndex = request.getParameter("postingTypeIndex");
        PostingType postingType = PostingType.getFromIndex(Integer.parseInt(postingTypeIndex));
        // 设置作者
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        wht.jly.forum.domain.User dbUser = userService.findByUsername(user.getUsername());

        posting.setPostingType(postingType)
                .setPostedTime(new Date())
                .setUpdateTime(new Date())
                .setAuthorId(dbUser.getId());
        // 执行保存
        Posting dbPosting = postingService.save(posting);

        log.info("用户【{}】 发帖 【{}】 成功", user.getUsername(), dbPosting);

        if (dbPosting != null) {
            return JsonData.buildSuccess("发帖成功", dbPosting);
        }
        return JsonData.build(400, "发帖失败，请刷新重试", null);
    }

}
